package com.cloud.order.service.impl;

import com.cloud.dto.CartDto;
import com.cloud.input.ProductInfoOutput;
import com.cloud.order.dto.OrderCreateDto;
import com.cloud.order.entity.OrderDetail;
import com.cloud.order.entity.OrderMaster;
import com.cloud.order.enums.OrderStatusEnum;
import com.cloud.order.enums.PayStatusEnum;
import com.cloud.order.exception.OrderException;
import com.cloud.order.repository.OrderDetailRepository;
import com.cloud.order.repository.OrderMasterRepository;
import com.cloud.order.service.OrderServiceInf;
import com.cloud.order.util.KeyUtils;
import com.cloud.product.ProductClient;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * describe:
 *
 * @author zhanghaixuan
 * @date 2018/09/11
 **/
@Service
public class OrderServiceImpl implements OrderServiceInf {

    @Autowired
    private ProductClient productClient;

    @Autowired
    private OrderDetailRepository orderDetailRepository;

    @Autowired
    private OrderMasterRepository orderMasterRepository;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderCreateDto create(OrderCreateDto orderCreateDto) {
        /**
         * 生成orderId
         */
        String uniqueLey = KeyUtils.getUniqueLey();

        /**
         * 获取商品信息(调用商品总价)
         */
        List<String> collect = orderCreateDto.getOrderDetailList().stream()
                .map(OrderDetail::getProductId).collect(Collectors.toList());


        List<ProductInfoOutput> productByIds = productClient.findProductByIds(collect);

        BigDecimal orderAmout = new BigDecimal(0);
        /**
         * 计算总价
         */
        for (OrderDetail orderDetail : orderCreateDto.getOrderDetailList()) {
            Integer productQuantity = orderDetail.getProductQuantity();

            for (ProductInfoOutput productById : productByIds) {
                if(productById.getProductId().equals(orderDetail.getProductId())){
                    orderAmout = orderAmout.add(productById.getProductPrice()
                            .multiply(new BigDecimal(productQuantity)));

                    BeanUtils.copyProperties(productById,orderDetail);
                    orderDetail.setOrderId(uniqueLey);
                    orderDetail.setDetailId(KeyUtils.getUniqueLey());
                    /**
                     * 订单详情入库
                     */
                    orderDetailRepository.save(orderDetail);
                }
            }
        }
        /**
         * 扣库存
         */

        List<CartDto> cartDtos = orderCreateDto.getOrderDetailList().stream()
                .map(e -> new CartDto(e.getProductId(),e.getProductQuantity())).collect(Collectors.toList());

        productClient.decreaseStock(cartDtos);

        /**
         * 生成订单
         */
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderCreateDto,orderMaster);
        orderMaster.setOrderId(uniqueLey);
        orderMaster.setOrderAmount(orderAmout);
        orderMaster.setOrderStatus(OrderStatusEnum.NEW.getCode());
        orderMaster.setPayStatus(PayStatusEnum.WAIT.getCode());

        orderMasterRepository.save(orderMaster);
        BeanUtils.copyProperties(orderMaster,orderCreateDto);
        return orderCreateDto;
    }

	@Override
	public OrderCreateDto finish(String orderId) {
		Optional<OrderMaster> byId = orderMasterRepository.findById(orderId);

		if(!byId.isPresent()){
			throw new OrderException("查询不到订单");
		}

		OrderMaster orderMaster = byId.get();

		if(!OrderStatusEnum.NEW.equals(orderMaster.getOrderStatus())){
			throw new OrderException("订单状态失败");
		}

		orderMaster.setOrderStatus(OrderStatusEnum.FINISHED.getCode());
		orderMasterRepository.save(orderMaster);

		OrderCreateDto orderCreateDto = new OrderCreateDto();
		BeanUtils.copyProperties(orderMaster,orderCreateDto);
		return orderCreateDto;
	}

	@RabbitListener(queuesToDeclare = @Queue("myQueue"))
	public void process(String message){
		System.out.println("MqRecevier:"+message);
	}
}
